﻿using System;
using System.Collections.Generic;
using System.Diagnostics.CodeAnalysis;
using System.Linq;
using System.Security.Principal;
using System.Web;
using System.Web.Mvc;
using System.Web.Routing;
using System.Web.Security;
using RMS.Models;
using System.Text;

using System.Web.Profile;

namespace RMS.Controllers
{
    public class AccountController : Controller
    {
        RMSDataClassesDataContext db = new RMSDataClassesDataContext();

        public IFormsAuthenticationService FormsService { get; set; }
        public IMembershipService MembershipService { get; set; }

        protected override void Initialize(RequestContext requestContext)
        {
            if (FormsService == null) { FormsService = new FormsAuthenticationService(); }
            if (MembershipService == null) { MembershipService = new AccountMembershipService(); }

            base.Initialize(requestContext);
        }

        // **************************************
        // URL: /Account/LogOn
        // **************************************

        public ActionResult LogOn()
        {
            return View();
        }

        [HttpPost]
        public ActionResult LogOn(LogOnModel model, string returnUrl)
        {
            if (ModelState.IsValid)
            {
                if (MembershipService.ValidateUser(model.UserName, model.Password))
                {
                    FormsService.SignIn(model.UserName, model.RememberMe);
                    if (Url.IsLocalUrl(returnUrl))
                    {
                        return Redirect(returnUrl);
                    }
                    else
                    {
                        return RedirectToAction("Index", "Home");
                    }
                }
                else
                {
                    ModelState.AddModelError("", "The user name or password provided is incorrect.");
                }
            }

            // If we got this far, something failed, redisplay form
            return View(model);
        }

        // **************************************
        // URL: /Account/LogOff
        // **************************************

        public ActionResult LogOff()
        {
            FormsService.SignOut();

            return RedirectToAction("Index", "Home");
        }

        // **************************************
        // URL: /Account/Register
        // **************************************
        public ActionResult AllUser()
        {
            return View(db.Users);
        }
        public ActionResult Register()
        {
            ViewBag.PasswordLength = MembershipService.MinPasswordLength;
            ViewData["companies"] = db.Companies.AsEnumerable();
            return View();
        }

        [HttpPost]
        public ActionResult Register(RegisterModel model, int? companyId, string companyName, string name,string role)
        {
            if (ModelState.IsValid)
            {
                // Attempt to register the user
                MembershipCreateStatus createStatus = MembershipService.CreateUser(model.UserName, model.Password, model.Email);

                if (createStatus == MembershipCreateStatus.Success)
                {
                    if (role != "Administrator")
                    {
                        Roles.AddUserToRole(model.UserName,role);
                    }
                    FormsService.SignIn(model.UserName, false /* createPersistentCookie */);

                    if (companyId.HasValue)
                    {
                        db.Users.InsertOnSubmit(new User
                        {
                            UserName = model.UserName,
                            Name = name
                        });
                        db.SubmitChanges();
                    }
                    else
                    {
                        User newUser = new User
                        {
                            UserName = model.UserName,
                            Name = name
                        };
                        db.Users.InsertOnSubmit(newUser);
                        db.SubmitChanges();
                        if (!String.IsNullOrEmpty(companyName))
                        {
                            Random r = new Random();
                            string legalChars = "1234567890";
                            StringBuilder sb = new StringBuilder();
                            for (int i = 1; i <= 4; i++)
                            {
                                sb.Append(legalChars.Substring(r.Next(0, legalChars.Length - 1), 1));
                            }
                            Company newCompany = new Company
                            {
                                FouderUserId = newUser.Id,
                                Name = companyName,
                                PassCode = sb.ToString()
                            };
                            
                            db.Companies.InsertOnSubmit(newCompany);
                            db.SubmitChanges();

                            foreach (ProblemGroup g in db.ProblemGroups)
                            {
                                db.CompanyProblemLimits.InsertOnSubmit(new CompanyProblemLimit
                                {
                                    CompanyId = newCompany.Id,
                                    ProblemGroupId = g.Id,
                                    Limit = 0
                                });
                                db.SubmitChanges();
                            }


                            newUser.CompanyId = newCompany.Id;
                            db.SubmitChanges();
                        }
                    }
                    
                    return RedirectToAction("SelfDetails", "User");
                }
                else
                {
                    ModelState.AddModelError("", AccountValidation.ErrorCodeToString(createStatus));
                }
            }
            // If we got this far, something failed, redisplay form
            ViewBag.PasswordLength = MembershipService.MinPasswordLength;
            return View(model);
        }

        // **************************************
        // URL: /Account/ChangePassword
        // **************************************

        [Authorize]
        public ActionResult ChangePassword()
        {
            ViewBag.PasswordLength = MembershipService.MinPasswordLength;
            return View();
        }

        [Authorize]
        [HttpPost]
        public ActionResult ChangePassword(ChangePasswordModel model)
        {
            if (ModelState.IsValid)
            {
                if (MembershipService.ChangePassword(User.Identity.Name, model.OldPassword, model.NewPassword))
                {
                    return RedirectToAction("ChangePasswordSuccess");
                }
                else
                {
                    ModelState.AddModelError("", "The current password is incorrect or the new password is invalid.");
                }
            }

            // If we got this far, something failed, redisplay form
            ViewBag.PasswordLength = MembershipService.MinPasswordLength;
            return View(model);
        }

        // **************************************
        // URL: /Account/ChangePasswordSuccess
        // **************************************

        public ActionResult ChangePasswordSuccess()
        {
            return View();
        }

    }
}
